import 'package:flutter/material.dart';

/// Dart函数示例
class FunctionsExample extends StatefulWidget {
  const FunctionsExample({super.key});

  @override
  State<FunctionsExample> createState() => _FunctionsExampleState();
}

class _FunctionsExampleState extends State<FunctionsExample> {
  String result = '点击下方按钮查看函数示例';

  // 标准函数
  String greet(String name) {
    return 'Hello, $name!';
  }

  // 箭头函数
  String greetArrow(String name) => 'Hello, $name!';

  // 可选位置参数
  String introduce(String name, [int? age, String? city]) {
    String intro = '我是$name';
    if (age != null) intro += '，今年$age岁';
    if (city != null) intro += '，来自$city';
    return intro;
  }

  // 命名参数
  String createUser({required String name, int age = 18, String? email}) {
    String user = '用户名: $name, 年龄: $age';
    if (email != null) user += ', 邮箱: $email';
    return user;
  }

  // 返回函数的函数
  Function makeMultiplier(int multiplier) {
    return (int value) => value * multiplier;
  }

  void _demonstrateBasicFunctions() {
    setState(() {
      result = '''
【基本函数】

1. 标准函数:
String greet(String name) {
  return 'Hello, \$name!';
}
调用: ${greet('Alice')}

2. 箭头函数 (适合单表达式):
String greetArrow(String name) => 'Hello, \$name!';
调用: ${greetArrow('Bob')}

两者功能相同，箭头函数更简洁。
      ''';
    });
  }

  void _demonstrateOptionalParameters() {
    setState(() {
      result = '''
【可选参数】

1. 可选位置参数 (用方括号):
String introduce(String name, [int? age, String? city]) {
  // ...
}

调用示例:
${introduce('张三')}
${introduce('李四', 25)}
${introduce('王五', 30, '北京')}

2. 命名参数 (用花括号):
String createUser({
  required String name, 
  int age = 18, 
  String? email
}) { ... }

调用示例:
${createUser(name: 'Alice')}
${createUser(name: 'Bob', age: 25)}
${createUser(name: 'Charlie', age: 30, email: 'c@example.com')}
      ''';
    });
  }

  void _demonstrateHigherOrderFunctions() {
    List<int> numbers = [1, 2, 3, 4, 5];

    // map - 转换每个元素
    var doubled = numbers.map((n) => n * 2).toList();

    // where - 过滤元素
    var evens = numbers.where((n) => n % 2 == 0).toList();

    // reduce - 归约为单个值
    var sum = numbers.reduce((a, b) => a + b);

    setState(() {
      result = '''
【高阶函数】
高阶函数可以接收函数作为参数或返回函数。

原始列表: $numbers

1. map - 转换每个元素:
numbers.map((n) => n * 2)
结果: $doubled

2. where - 过滤元素:
numbers.where((n) => n % 2 == 0)
结果: $evens

3. reduce - 归约求和:
numbers.reduce((a, b) => a + b)
结果: $sum
      ''';
    });
  }

  void _demonstrateClosures() {
    var doubler = makeMultiplier(2);
    var tripler = makeMultiplier(3);

    setState(() {
      result = '''
【闭包】
闭包是可以访问其词法作用域中变量的函数。

Function makeMultiplier(int multiplier) {
  return (int value) => value * multiplier;
}

创建不同的乘法器:
var doubler = makeMultiplier(2);
var tripler = makeMultiplier(3);

使用:
doubler(5) = ${doubler(5)}
doubler(10) = ${doubler(10)}
tripler(5) = ${tripler(5)}
tripler(10) = ${tripler(10)}

每个闭包都记住了自己的 multiplier 值！
      ''';
    });
  }

  void _demonstrateAnonymousFunctions() {
    List<String> names = ['Alice', 'Bob', 'Charlie'];

    // 使用匿名函数
    var uppercased = names.map((name) {
      return name.toUpperCase();
    }).toList();

    // 简洁的箭头函数
    var lowercased = names.map((name) => name.toLowerCase()).toList();

    setState(() {
      result = '''
【匿名函数】
也叫lambda函数，没有名称的函数。

原始列表: $names

1. 多行匿名函数:
names.map((name) {
  return name.toUpperCase();
})
结果: $uppercased

2. 箭头匿名函数:
names.map((name) => name.toLowerCase())
结果: $lowercased
      ''';
    });
  }

  void _demonstrateTypedFunctions() {
    // 函数类型
    int Function(int, int) adder = (a, b) => a + b;
    int Function(int, int) multiplier = (a, b) => a * b;

    // 函数作为参数
    int calculate(int a, int b, int Function(int, int) operation) {
      return operation(a, b);
    }

    setState(() {
      result = '''
【函数类型】
可以将函数赋值给变量或作为参数。

1. 定义函数类型变量:
int Function(int, int) adder = (a, b) => a + b;
int Function(int, int) multiplier = (a, b) => a * b;

2. 函数作为参数:
int calculate(int a, int b, int Function(int, int) operation) {
  return operation(a, b);
}

使用:
calculate(5, 3, adder) = ${calculate(5, 3, adder)}
calculate(5, 3, multiplier) = ${calculate(5, 3, multiplier)}
      ''';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dart 函数'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.orange.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '⚡ 函数概述',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 8),
                    Text(
                      'Dart中函数是一等公民，功能强大：\n'
                      '• 标准函数和箭头函数\n'
                      '• 可选参数：位置参数和命名参数\n'
                      '• 高阶函数：接收或返回函数\n'
                      '• 闭包：捕获外部变量\n'
                      '• 匿名函数：lambda表达式',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 代码示例区域
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                '''// 标准函数
String greet(String name) {
  return 'Hello, \$name!';
}

// 箭头函数
String greet(String name) => 'Hello, \$name!';

// 可选位置参数
void say(String msg, [String? from]) { }

// 命名参数
void create({required String name, int age = 0}) { }

// 高阶函数
list.map((item) => item * 2);
list.where((item) => item > 10);

// 匿名函数
var fn = (x) => x * 2;''',
                style: TextStyle(
                  fontFamily: 'monospace',
                  fontSize: 13,
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 交互按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _demonstrateBasicFunctions,
                  icon: const Icon(Icons.functions),
                  label: const Text('基本函数'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateOptionalParameters,
                  icon: const Icon(Icons.settings),
                  label: const Text('可选参数'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateHigherOrderFunctions,
                  icon: const Icon(Icons.layers),
                  label: const Text('高阶函数'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateClosures,
                  icon: const Icon(Icons.lock),
                  label: const Text('闭包'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateAnonymousFunctions,
                  icon: const Icon(Icons.code),
                  label: const Text('匿名函数'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateTypedFunctions,
                  icon: const Icon(Icons.type_specimen),
                  label: const Text('函数类型'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 结果展示区域
            Card(
              elevation: 4,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                constraints: const BoxConstraints(minHeight: 150),
                child: Text(
                  result,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'monospace',
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

